package com.lld.im.service.group.mq;

import com.alibaba.fastjson.JSONObject;
import com.lld.im.common.constants.Constants;
import com.lld.im.common.enums.commond.GroupEventCommand;
import com.lld.im.common.model.message.GroupMessageContent;
import com.lld.im.service.group.service.GroupMessageServer;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class GroupMsgReceiver {

    @Autowired
    private GroupMessageServer groupMessageServer;


    /**
     * durable 是否持久化
     * concurrency 并发消费者的数量为1，表示同时只有一个消费者处理消息
     * Channel: 当前与mq的连接通道 用来进行ack确认(默认spring会自动确认)
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = Constants.RabbitConstants.Im2GroupService, durable = "true"),
                    exchange = @Exchange(value = Constants.RabbitConstants.Im2GroupService, durable = "true")
            ),concurrency = "1"
    )
    public void onReceiverChart(@Payload Message message,
                                @Headers Map<String,Object> headers, Channel channel) throws Exception {
        //dataStr : 包含一个command dataStr
        String dataStr = new String(message.getBody(), "utf-8");
        log.info("接收到 groupMsg==={}",dataStr);
        JSONObject jsonObject = JSONObject.parseObject(dataStr);
        //根据不同命令 来实现消息的不同投递
        Integer command = jsonObject.getInteger("command");
        //TODO 对于群聊消息 需要判断群状态 以及发送者身份
        if (command == GroupEventCommand.MSG_GROUP.getCommand()) {
            GroupMessageContent messageContent = jsonObject.toJavaObject(GroupMessageContent.class);
            groupMessageServer.process(messageContent);
        }
    }
}
